package com.leslie.wukong.common.security.interceptor;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.leslie.wukong.common.core.constants.CacheConstants;
import com.leslie.wukong.common.core.constants.HttpStatus;
import com.leslie.wukong.common.core.constants.SecurityConstants;
import com.leslie.wukong.common.core.domain.SysUser;
import com.leslie.wukong.common.core.exception.ServiceException;
import com.leslie.wukong.common.core.properties.JwtProperties;
import com.leslie.wukong.common.core.utils.JwtUtil;
import com.leslie.wukong.common.redis.service.RedisService;
import com.leslie.wukong.common.security.context.SecurityContextHolder;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;
    private final RedisService redisService;
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("令牌为空", HttpStatus.UNAUTHORIZED);
        }
        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            String tokenBefore = (String) claims.get(SecurityConstants.USER_KEY);
            Object cacheObject = redisService.getCacheObject(this.getTokenKey(tokenBefore));
            SysUser sysUser = JSON.parseObject(cacheObject.toString(), SysUser.class);
            SecurityContextHolder.setUserId(sysUser.getUserId());
            SecurityContextHolder.set(SecurityConstants.LOGIN_USER, sysUser);
            log.info("当前用户id：{},用户昵称:{}", sysUser.getUserId(), sysUser.getNickName());
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            throw new ServiceException("令牌校验失败", HttpStatus.UNAUTHORIZED);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //程序收尾,把ThreadLocal中的iq给删除掉,不让后面使用这个线程的时候获取到错误的数据
        SecurityContextHolder.remove();
    }

    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}
